import cv2
# device代表调用的摄像头
def vidDetect(device):
    id = input("请输入采集对象的序号：")

    # 加载xml文件生成分类器
    face_detector = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')

    # img = cvs2.imread(filename) -> 摄像头获取
    cap = cv2.VideoCapture(device) # 电脑摄像头

    while cap.isOpened():
        ret,frame = cap.read()
        # 使用INTER_AREA插值法把图像的宽和高缩小为原来的一半
        frame = cv2.resize(frame,None,fx = 0.5,fy=0.5,interpolation=cv2.INTER_AREA)
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)   #转换成灰度文件

        # scaleFactor:图像缩小的比例
        face_rects = face_detector.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=3)

        # 用矩形框出每张人脸
        for(x,y,w,h) in face_rects:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)  # 蓝色框（B=255，G=R=0）
        cv2.imshow('Face Detector',frame)
        k = cv2.waitKey(1)

        if k == ord('s') or k == ord('S'):
            save_path = 'C:/Users/shouw/Desktop/tmp/viddesou/'
            cv2.imwrite(save_path + 'vidface' + str(id) + '.jpg',frame)
            break
        elif k & 0xff == ord('q') or k & 0xff == ord('Q'):
            break
    cv2.destroyAllWindows()
vidDetect(0)